package ltd.newbee.mall.order.service.impl;

import jakarta.annotation.Resource;
import ltd.newbee.mall.order.entity.Order;
import ltd.newbee.mall.order.entity.OrderItem;
import ltd.newbee.mall.order.mapper.OrderItemMapper;
import ltd.newbee.mall.order.mapper.OrderMapper;
import ltd.newbee.mall.order.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createOrder(List<OrderItem> items) {
        String orderNo = UUID.randomUUID().toString().replace("-", "").substring(0, 18).toUpperCase();
        int total = items.stream().mapToInt(i -> (i.getSellingPrice() == null ? 0 : i.getSellingPrice()) * (i.getGoodsCount() == null ? 1 : i.getGoodsCount())).sum();
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(0L);
        order.setTotalPrice(total);
        order.setPayStatus(0);
        order.setPayType(0);
        order.setOrderStatus(0);
        orderMapper.insert(order);
        for (OrderItem i : items) { i.setOrderId(order.getOrderId()); }
        if (!items.isEmpty()) { orderItemMapper.batchInsert(items); }
        return orderNo;
    }

    @Override
    public Order findByOrderNo(String orderNo) { return orderMapper.findByOrderNo(orderNo); }

    @Override
    public List<Order> findPage(int page, int size) {
        int offset = Math.max(page - 1, 0) * Math.max(size, 1);
        return orderMapper.findPage(offset, size);
    }

    @Override
    public List<OrderItem> findItems(String orderNo) { return orderItemMapper.findByOrderNo(orderNo); }
}


